﻿using System.Windows.Forms;
using Microsoft.Data.ConnectionUI;
using System;

namespace SPDbFileExtractor.Framework.Code
{
    public static class ConnectionManager
    {
        /// <summary>
        /// Gets or sets the connection string.
        /// </summary>
        /// <value>
        /// The connection string.
        /// </value>
        public static string ConnectionString { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether [connection valid].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [connection valid]; otherwise, <c>false</c>.
        /// </value>
        public static bool ConnectionValid { get; set; }

        /// <summary>
        /// Sets up the connection dialog.
        /// </summary>
        public static void SetupConnection()
        {
            try
            {
                DataConnectionDialog dcd = new DataConnectionDialog();
                dcd.DataSources.Add(DataSource.SqlDataSource);

                if (DataConnectionDialog.Show(dcd) == DialogResult.OK)
                {
                    if (dcd.ConnectionString == null || !dcd.ConnectionString.Contains("Initial Catalog"))
                    {
                        ConnectionValid = false;
                        Utils.ShowWinFormError("You must select a content database before continuing.");
                    }
                    else
                    {
                        var versionValid = ContentDbManager.VerifyDbVersion(dcd.ConnectionString);

                        if (!versionValid)
                        {
                            ConnectionValid = false;
                            Utils.ShowWinFormError("Selected DB is not content DB or is incorrect version.");
                        }
                        else
                        {
                            ConnectionValid = true;
                            ConnectionString = dcd.ConnectionString;
                        }
                    }
                }
                else
                {
                    ConnectionValid = false;
                }
            }
            catch (Exception ex)
            {
                Utils.ShowWinFormError(ex);
            }
        }
    }
}
